package com.aier.proxy.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.aier.admin.entity.IcCard;
import com.aier.admin.entity.mapper.IcCardRowMapper;
import com.aier.common.common.Constant;
import com.aier.common.dao.ICommonDAO;
import com.aier.entrance.common.EntranceICFinalData;
import com.aier.proxy.service.IUserBindIcardService;
import com.aier.school.entity.School;
import com.aier.school.entity.SchoolIcCard;
import com.aier.school.entity.mapper.SchoolIcCardRowMapper;
import com.aier.school.entity.mapper.SchoolRowMapper;
import com.aier.user.common.UserIcardData;
import com.aier.user.service.IUserService;

@Component("userBindIcardService")
public class UserBindIcardServiceImpl_J implements IUserBindIcardService {

    @Resource(name = "commonDao")
    private ICommonDAO commonDao;

    @Resource(name = "userService")
    private IUserService userService;
    
//    @Resource(name = "homeService")
//    private IHomeService homeService;
    
    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }
    

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
    
//    public void setHomeService(IHomeService homeService) {
//        this.homeService = homeService;
//    }

    // 普通用户绑定IC卡
    @Override
    public int updateUserIcard(Long uid, Long cid, Long icid) {
        Integer sid = (Integer) commonDao.listByObject(
                "select c.sid from classes as c where c.cid=?",
                new Object[] { cid }, new RowMapper<Integer>() {
                    @Override
                    public Integer mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getInt("sid");
                    }
                });
        if (null != sid
                && sid > 0
                && commonDao
                        .update("update school_icard si inner join ic_card as ic on si.icid=ic.icid " +
                        		"set si.cid=?,ic.icstate=?,ic.icpuser=?,si.state=? where ic.icid =? and si.sid=?",
                                new Object[] { cid,
                                    EntranceICFinalData.IC_STATE_USER_ON,
                                    EntranceICFinalData.IC_PURPOSE_USER_ON,
                                    UserIcardData.SI_STATE_ON, icid, sid }) > 0) {
            commonDao
                    .update("insert into classes_user_icard (cid,uid,icid) values (?,?,?)",
                            new Object[] { cid, uid, icid });
            commonDao
                    .update("insert into school_user_icard (sid,uid,icid) values (?,?,?)",
                            new Object[] { sid, uid, icid });
            return Constant.num_10001;
        } else {
            return Constant.num_10000;
        }
    }

    @Override
    public int removeUserIcard(Long uid, Long cid, boolean revocer) {
        Integer sid = (Integer) commonDao.listByObject(
                "select c.sid from classes as c where c.cid=?",
                new Object[] { cid }, new RowMapper<Integer>() {
                    @Override
                    public Integer mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getInt("sid");
                    }
                });
        if (null == sid) {
            return -1;
        }
        if (revocer) {
            // 全部回收
            commonDao
                    .update("update school_icard as si set state=? WHERE si.sid=? and si.icid in " +
                    		"(select sui.icid from school_user_icard as sui where sui.uid=? and sui.sid=?)",
                            new Object[] { UserIcardData.SI_STATE_NOTACTIVATED,sid, uid, sid });
        } else {
            // 全部删除
            commonDao
                    .update("update school_icard as si set state=? WHERE si.sid=? and si.icid in " +
                    		"(select sui.icid from school_user_icard as sui where sui.uid=? and sui.sid=?)",
                            new Object[] { UserIcardData.SI_STATE_REMOVE, sid,uid, sid });
        }

        deleteSCICard(uid, sid, cid);

        return 1;
    }

    /**
     * 删除学校班级ic卡数据
     * 
     * @param uid
     * @param sid
     * @param cid
     */
    private void deleteSCICard(long uid, long sid, long cid, long icid) {
        commonDao
                .update("DELETE from school_user_icard  WHERE uid=? and sid=? and icid=?",
                        new Object[] { uid, sid, icid });
        commonDao
                .update("delete from classes_user_icard where uid=? and cid=? and icid=?",
                        new Object[] { uid, cid, icid });
    }

    /**
     * 删除学校班级ic卡数据
     * 
     * @param uid
     * @param sid
     * @param cid
     */
    private void deleteSCICard(long uid, long sid, long cid) {

        commonDao.update(
                "DELETE from school_user_icard  WHERE uid=? and sid=?",
                new Object[] { uid, sid });
        commonDao.update(
                "delete from classes_user_icard where uid=? and cid=?",
                new Object[] { uid, cid });
    }

    // 根据ic卡号返会school_icard对象
    @Override
    public SchoolIcCard searchSchoolIcardByCardNum(String ichead, String icbody,
            String icfoot) {
        return (SchoolIcCard) commonDao
                .listByObject(
                        "SELECT si.* FROM school_icard as si LEFT JOIN ic_card as ic on si.icid=ic.icid " +
                        "WHERE ic.ichead=? AND ic.icbody=? AND icfoot=?",
                        new Object[] { ichead, icbody, icfoot },
                        new SchoolIcCardRowMapper());
    }

    // 根据ic卡号返会IC卡ID
    @Override
    public IcCard searchIcidByCardNum(String ichead, String icbody,
            String icfoot) {

        return (IcCard) commonDao
                .listByObject(
                        "select icid from ic_card where ichead=? and icbody=? and icfoot=?",
                        new Object[] { ichead, icbody, icfoot },
                        new IcCardRowMapper());
    }

    // 根据ic卡号返会IC卡所属学校
    @Override
    public School searchSchoolByIcid(Long icid) {

        return (School) commonDao
                .listByObject(
                        "select * from school where sid=(select sid from school_icard where icid=?)",
                        new Object[] { icid }, new SchoolRowMapper());
    }

    // 教师绑定IC卡
    @Override
    public int updateTeacherIcard(Long tid, Long icid) {
        if (commonDao.update("update school_icard si inner join ic_card as ic " +
                		"on si.icid=ic.icid set ic.icstate=?,ic.icpteacher=?,si.state=?,si.bsdate=? where ic.icid=?",
                        new Object[] { EntranceICFinalData.IC_STATE_USER_ON,
                            EntranceICFinalData.IC_PURPOSE_TECHER_ON,
                            UserIcardData.SI_STATE_ON,
                            new Timestamp(new Date().getTime()), icid }) > 0) {
            commonDao.update("insert into school_teacher_icard (sid,tid,icid) values ((select sid from teacher_school where tid=?),?,?)",
                            new Object[] { tid, tid, icid });
            return Constant.num_10001;
        } else {
            return Constant.num_10000;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<IcCard> searchIcidByIcBody(Integer pid, String ichead,
            String icbodyMin, String icbodyMax) {

        return (List<IcCard>) commonDao
                .list("select ic.icid from ic_card as ic where ic.ichead=? and (?<=ic.icbody and ?>=ic.icbody) " +
                		"and ic.icid in (select pi.icid from proxy_icard as pi left join ic_card as tic on tic.icid=pi.icid where pi.pid=?)",
                        new Object[] { ichead, icbodyMin, icbodyMax, pid },
                        new IcCardRowMapper());
    }
    @Override
    public int updateRevocerUserIcard(Long uid, Long cid, Long icid) {
        Integer sid = (Integer) commonDao.listByObject(
                "select c.sid from classes as c where c.cid=?",
                new Object[] { cid }, new RowMapper<Integer>() {
                    @Override
                    public Integer mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getInt("sid");
                    }
                });
        if (null == sid) {
            return -1;
        }

        commonDao
                .update("update school_icard as si set state=?,cid=null WHERE si.sid=? and si.icid=?",
                        new Object[] { UserIcardData.SI_STATE_NOTACTIVATED,sid, icid });
        deleteSCICard(uid, sid, cid, icid);
        return 1;
    }

    @Override
    public int removeUserIcard(Long uid, Long cid, Long icid) {
        Integer sid = (Integer) commonDao.listByObject(
                "select c.sid from classes as c where c.cid=?",
                new Object[] { cid }, new RowMapper<Integer>() {
                    @Override
                    public Integer mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getInt("sid");
                    }
                });
        if (null == sid) {
            return -1;
        }

        commonDao
                .update("update school_icard as si set state=? WHERE si.sid=? and si.icid=?",
                        new Object[] { UserIcardData.SI_STATE_REMOVE, sid, icid });
        deleteSCICard(uid, sid, cid, icid);
        return 1;
    }

    /**
     * 家长绑定IC卡
     * 
     * @param uid
     * @param icid
     * @return
     */
    @Override
    public int updateParentsIcard(Long uid, String ichead, String icbody,
            String icfoot) {
        SchoolIcCard si = null;
        try {
            si = searchSchoolIcardByCardNum(ichead, icbody, icfoot);
        } catch (Exception e) {
            e.printStackTrace();
            //卡不能使用
            return Constant.num_10002;
        }

        if (null == si) {
            //卡不能使用
            return Constant.num_10002;
        }

        if (commonDao
                .update("update school_icard si inner join ic_card as ic on si.icid=ic.icid " +
                		"set ic.icstate=?,ic.icpteacher=?,si.state=?,si.bsdate=? where ic.icid=?",
                        new Object[] { EntranceICFinalData.IC_STATE_USER_ON,
                            EntranceICFinalData.IC_PURPOSE_USER_ON,
                            UserIcardData.SI_STATE_ON,
                            new Timestamp(new Date().getTime()),
                                si.getIcid() }) > 0) {

            commonDao.update("insert into school_user_icard (sid,uid,icid) values (?,?,?)",
                            new Object[] { si.getSid(), uid, si.getIcid() });
            

            return Constant.num_10001;
        } else {
            return Constant.num_10000;
        }

        
    }

//    /**
//     * 家长帮宝宝绑定IC卡
//     * @param ichead
//     * @param icbody
//     * @param icfoot
//     * @return
//     */
//    @Override
//    public int updateChildIcard(String ichead, String icbody, String icfoot,Long ruid,String hname) {
//        SchoolIcard si = null;
//        Long uid = null;
//        try {
//            si = searchSchoolIcardByCardNum(ichead, icbody, icfoot);
//        } catch (Exception e) {
//            e.printStackTrace();
//            //卡不能使用
//            return Constant.num_10002;
//        }
//        if (null == si) {
//            //卡不能使用
//            return Constant.num_10002;
//        }
//        
//        if (null != userService.searchUserAccount(ichead+icbody)) {
//            if(null != userService.searchUserAccount(ichead+icbody+RandomUtil.genRandomNum(Constant.num_8, RandomUtil.PWD_TYPE_NUM_AND_CHAR))){
//                updateChildIcard(ichead, icbody, icfoot,ruid,hname);
//            }else{
//                uid = userService.insertUser(ichead+icbody+RandomUtil.genRandomNum(Constant.num_8, RandomUtil.PWD_TYPE_NUM_AND_CHAR), icfoot, true);
//                
//            }
//            
//        }else{
//            // 默认密码为卡号后4位随机码
//            uid = userService.insertUser(ichead+icbody,icfoot, true);
//        }
//        
//        if (commonDao
//                .update("update school_icard si inner join ic_card as ic on si.icid=ic.icid " +
//                		"set ic.icstate=?,ic.icpteacher=?,si.state=?,si.bsdate=? where ic.icid=?",
//                        new Object[] { EntranceICFinalData.IC_STATE_USER_ON,
//                            EntranceICFinalData.IC_PURPOSE_USER_ON,
//                            UserIcardData.SI_STATE_ON,
//                            new Timestamp(new Date().getTime()),
//                                si.getIcid() }) > 0) {
//
//            commonDao
//                    .update("insert into school_user_icard (sid,uid,icid) values (?,?,?)",
//                            new Object[] { si.getSid(), uid, si.getIcid() });
//            
//            //给帮帮绑定监护人关系
//            insertRelationShip(uid, ruid, hname);
//
//            return Constant.num_10001;
//        } else {
//            return Constant.num_10000;
//        }
//        
//    }


//    /**
//     * 给宝宝添加监护人
//     * @param buid 宝宝id
//     * @param ruid 监护人id
//     * @param hname 组成家庭名称
//     * @return
//     */
//    @Override
//    public int insertRelationShip(Long buid, Long ruid,String hname) {
//        if (0 >= commonDao
//                .countByQuali(
//                        "select rnid from home_relationship where buid=? and ruid=? and guardian=?",
//                        new Object[] {
//                            buid,
//                            ruid,
//                            IHomeRelationshipService.HOMERELATIONSHIP_GUARDIAN_ONE })) {
//            // 账号不是监护人,给该账号添加成该学生的监护人
//            if (Constant.num_10001 != homeService.insertCreateHome(buid, hname,
//                    UserHomeData.HOME_MEM_UNKNOWN, ruid)) {
//                
//                //throw new RuntimeException("家庭创建失败");
//                return Constant.num_10000;
//                
//            }
//            return Constant.num_10001;
//        }else{
//            return Constant.num_10000;
//        }
//    }


    
}
